<template>
  <div class="sse-container">
    <el-card class="message-card">
      <template #header>
        <div class="card-header">
          <span>实时数据监控</span>
          <el-tag :type="connectionStatus.type">{{ connectionStatus.text }}</el-tag>
        </div>
      </template>
      <div class="message-list">
        <div v-for="(message, index) in messages" :key="index" class="message-item">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="时间">{{ message.time }}</el-descriptions-item>
            <el-descriptions-item label="数值">{{ message.value }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { getToken } from '@/utils/auth'
const url = import.meta.env.VITE_APP_BASE_API
const messages = ref([])
const connectionStatus = ref({
  type: 'info',
  text: '未连接'
})

let eventSource = null

const initEventSource = () => {
  eventSource = new EventSourcePolyfill(url + '/sse-connect?userId=1', {
    headers: {
      'Authorization': 'Bearer ' + getToken(),  // 替换为您的实际 token

    }
  })

  eventSource.onopen = function() {
    connectionStatus.value = {
      type: 'success',
      text: '已连接'
    }
    ElMessage.success('SSE 连接成功')
  }

  eventSource.addEventListener('welcome', (event) => {
    ElMessage.success(event.data)
  })

  eventSource.addEventListener('system-metrics', (event) => {
    try {
      const data = JSON.parse(event.data)
      messages.value.unshift(data)
      // 只保留最新的10条消息
      if (messages.value.length > 5) {
        messages.value.pop()
      }
    } catch (error) {
      console.error('解析消息失败:', error)
    }
  })

  eventSource.onerror = function(err) {
    connectionStatus.value = {
      type: 'danger',
      text: '连接断开'
    }
    console.error('连接出错', err)
    ElMessage.error('SSE 连接断开')
  }
}

onMounted(() => {
  initEventSource()
})

onUnmounted(() => {
  if (eventSource) {
    console.log('关闭连接')
    eventSource.close()
  }
})
</script>

<style scoped>
.sse-container {
  padding: 20px;
}

.message-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-list {
  max-height: 600px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 10px;
}

.message-item:last-child {
  margin-bottom: 0;
}
</style>
